package chatgpt

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
)

var (
	goroutineSpace = []byte("goroutine ")
	mu             sync.Mutex
	indentMap      = make(map[uint64]int)
)

func curGoroutineID() uint64 {
	// Capture the current stack trace
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]

	// Extract the goroutine ID
	b = bytes.TrimPrefix(b, goroutineSpace)
	i := bytes.IndexByte(b, ' ')
	if i < 0 {
		panic(fmt.Sprintf("No space found in %q", b))
	}
	b = b[:i]
	gid, err := strconv.ParseUint(string(b), 10, 64)
	if err != nil {
		panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
	}
	return gid
}

func printTrace(id uint64, name string, line int, arrow string, indent int) {
	// Create indentations
	indents := ""
	for i := 0; i < indent; i++ {
		indents += "    "
	}

	// Print the trace message
	fmt.Printf("g[%05d]:%s%s%s:%d\n", id, indents, arrow, name, line)
}

func Trace() func() {
	// Get the caller's details
	pc, _, line, ok := runtime.Caller(1)
	if !ok {
		panic("Unable to retrieve caller information")
	}

	fn := runtime.FuncForPC(pc)
	name := fn.Name()
	gid := curGoroutineID()

	// Update indentation level for this goroutine
	mu.Lock()
	indentMap[gid]++
	indentLevel := indentMap[gid]
	mu.Unlock()

	// Print entering trace
	printTrace(gid, name, line, "->", indentLevel)

	// Return a function to print exiting trace
	return func() {
		mu.Lock()
		indentMap[gid]--
		indentLevel := indentMap[gid]
		mu.Unlock()

		// Print exiting trace
		printTrace(gid, name, line, "<-", indentLevel)
	}
}

/*
	Key Changes:
	Variable Renaming: Made variable names more descriptive (indentMap instead of m).
	Comments: Added comments to explain the purpose of code sections.
	Removed Unnecessary Formatting: Simplified the color formatting and removed commented-out code to make the logic clearer.
	Error Handling Messages: Improved the clarity of panic messages.
	Synchronization: Ensured thread safety by locking around both read and write operations on the shared indentMap.
	This refactored version is more readable and maintains the original functionality.

*/
